package org.dreamwork.android.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import java.util.List;

/**
 * Created by game on 2017/3/8
 */
public abstract class AbstractListAdapter<T, H> extends BaseAdapter {
    protected List<T> data;
    protected Context context;
    private int layoutId;

    protected AbstractListAdapter (Context context, int layoutId) {
        this.context  = context;
        this.layoutId = layoutId;
    }

    public void setData (List<T> data) {
        this.data = data;
    }

    @Override
    public int getCount () {
        return data == null ? 0 : data.size ();
    }

    @Override
    public T getItem (int i) {
        return data == null ? null : data.get (i);
    }

    @Override
    public long getItemId (int i) {
        return i;
    }

    @Override
    @SuppressWarnings ("unchecked")
    public View getView (int position, View convertView, ViewGroup parent) {
        H holder;
        if (convertView == null) {
            convertView = LayoutInflater.from (context).inflate (layoutId, null);
            holder = holdUI (convertView);
            convertView.setTag (holder);
        } else {
            holder = (H) convertView.getTag ();
        }

        T value = getItem (position);
        fillUIData (holder, value, convertView);
        return convertView;
    }

    protected abstract H holdUI (View view);
    protected abstract void fillUIData (H holder, T value, View convertView);
}